package com.otaku.admin.security;

import com.otaku.admin.dao.UserMapper;
import com.otaku.admin.dao.entity.Permission;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.servlet.http.HttpServletRequest;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author: zzx
 * @date: 2018/10/16 9:54
 * @description: 权限访问控制
 */
@Component("rbacauthorityservice")
public class RbacAuthorityService {

    @Autowired
    private UserMapper userMapper;

    private static final Logger LOGGER = LoggerFactory.getLogger(RbacAuthorityService.class);

    public boolean hasPermission(HttpServletRequest request, Authentication authentication) {

        Object userInfo = authentication.getPrincipal();
        boolean hasPermission  = false;
        /**
         * @TODO 开发环境开通所有权限
         */
        if (userInfo instanceof UserDetails) {
            String username = ((UserDetails) userInfo).getUsername();
            List<Permission> listPermission = userMapper.findPermissionByUsername(username);
            //获取资源
            Set<String> urls = new HashSet();
            // 这些 url 都是要登录后才能访问，且其他的 url 都不能访问！
            for (Permission permission : listPermission) {
                urls.add(permission.getUrl());
            }
            AntPathMatcher antPathMatcher = new AntPathMatcher();
            for (String url : urls) {
                if (antPathMatcher.match(url, request.getRequestURI())) {
                    hasPermission = true;
                    break;
                }
            }
            return true;
//            return hasPermission;
        } else {
            return false;
        }
    }
}
